package com.xteam.xnetworkdisk.sys.controller;

import com.xteam.xnetworkdisk.utils.FileLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;

@RestController
@RequestMapping("xnetworkdiskBackground")
public class XNetWorkDiskBackgroundController {
    @Autowired
    private FileLocalUtils fileLocalUtils;
    /**
     * 文件预览
     * @param fileName
     * @return
     */
    @GetMapping("/preview/{fileName}")
    public ResponseEntity<StreamingResponseBody> previewFile(@PathVariable("fileName") String fileName) {
        try {
            String fullPath = fileLocalUtils.getFullPathBackground(fileName);
            InputStream inputStream = fileLocalUtils.getFilePreviewInputStream(fullPath);
            String contentType = Files.probeContentType(Paths.get(fullPath));
            contentType = contentType != null ? contentType : "application/octet-stream";

            // 如果文件类型是文本文件，添加字符编码
            if (contentType.startsWith("text")) {
                contentType += "; charset=UTF-8";
            }

            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_TYPE, contentType);
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + Paths.get(fullPath).getFileName() + "\"");

            StreamingResponseBody stream = outputStream -> {
                byte[] buffer = new byte[1024];
                int bytesRead;
                try {
                    while ((bytesRead = inputStream.read(buffer)) != -1) {
                        outputStream.write(buffer, 0, bytesRead);
                    }
                } catch (IOException e) {
                    throw new IOException("Error writing to output stream", e);
                } finally {
                    try {
                        inputStream.close(); // 确保在流操作完成后关闭输入流
                    } catch (IOException e) {
                        throw new IOException("Error closing input stream", e);
                    }
                }
            };

            return new ResponseEntity<>(stream, headers, HttpStatus.OK);
        } catch (IOException e) {
            // 处理文件读取异常
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        } catch (Exception e) {
            // 处理其他异常
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

}
